MongoDB Tutorial

Must Watch!



MustWatch






Install MongoDB Community Edition on Windows

Use this tutorial to install MongoDB Community Edition on Windows systems. Platform Support: Starting in version 3.6 MongoDB requires Windows Server 2008 R2, Windows 7, or later. Important: If you are running any edition of Windows Server 2008 R2 or Windows 7, please install a hotfix to resolve an issue with memory mapped files on Windows. Note: Starting in MongoDB 3.6, MongoDB binaries, mongod and mongos, bind to localhost by default. Previously, starting in MongoDB 2.6, only the binaries from the official MongoDB RPM (Red Hat, CentOS, Fedora Linux, and derivatives) and DEB (Debian, Ubuntu, and derivatives) packages bind to localhost by default. For more details, see Localhost Binding Compatibility Changes.

Requirements

MongoDB Community Edition requires Windows Server 2008 R2, Windows 7, or later. The .msi installer includes all other software dependencies and will automatically upgrade any older version of MongoDB installed using an .msi file. To find which version of Windows you are running, enter the following commands in the Command Prompt or Powershell: wmic os get caption wmic os get osarchitecture

Get MongoDB Community Edition

Note: To install a different version of MongoDB, please refer to that version's documentation. For example, see version 3.4. Download the latest production release of MongoDB from the MongoDB Download Center.

Install MongoDB Community Edition

Interactive Installation

In Windows Explorer, locate the downloaded MongoDB .msi file, which typically is located in the default Downloads folder. Double-click the .msi file. A set of screens will appear to guide you through the installation process. You may specify an installation directory if you choose the "Custom" installation option. Note: These instructions assume that you have installed MongoDB to C:\Program Files\MongoDB\Server\3.6\. During the installation process you will be given the option to install MongoDB Compass in addition to MongoDB Server. MongoDB is self-contained and does not have any other system dependencies. You can run MongoDB from any folder you choose. You may install MongoDB in any folder (e.g. D:\test\mongodb).

Unattended Installation

You may install MongoDB Community unattended on Windows from the command line using msiexec.exe.

Step 1: Open an Administrator command prompt.

Press the Win key, type cmd.exe, and press Ctrl + Shift + Enter to run the Command Prompt as Administrator. Execute the remaining steps from the Administrator command prompt.

Step 2: Install MongoDB for Windows.

Change to the directory containing the .msi installation binary of your choice and invoke: msiexec.exe /q /i mongodb-win32-x86_64-2008plus-ssl-3.6.0-signed.msi ^ INSTALLLOCATION="C:\Program Files\MongoDB\Server\3.6.0\" ^ ADDLOCAL="all" You can specify the installation location for the executable by modifying the INSTALLLOCATION value. By default, this method installs all MongoDB binaries. To install specific MongoDB component sets, you can specify them in the ADDLOCAL argument using a comma-separated list including one or more of the following component sets:
Component Set Binaries
Servermongod.exe
Routermongos.exe
Clientmongo.exe
MonitoringToolsmongostat.exe, mongotop.exe
ImportExportToolsmongodump.exe, mongorestore.exe, mongoexport.exe, mongoimport.exe
MiscellaneousToolsbsondump.exe, mongofiles.exe, mongoperf.exe
For instance, to install only the MongoDB utilities, invoke: msiexec.exe /q /i mongodb-win32-x86_64-2008plus-ssl-3.6.0-signed.msi ^ INSTALLLOCATION="C:\Program Files\MongoDB\Server\3.6.0\" ^ ADDLOCAL="MonitoringTools,ImportExportTools,MiscellaneousTools"

Run MongoDB Community Edition

Warning: Do not make mongod.exe visible on public networks without running in "Secure Mode" with the auth setting. MongoDB is designed to be run in trusted environments, and the database does not enable "Secure Mode" by default.

Step 1: Set up the MongoDB environment.

MongoDB requires a data directory to store all data. MongoDB's default data directory path is the absolute path \data\db on the drive from which you start MongoDB. Create this folder by running the following command in a Command Prompt: md \data\db You can specify an alternate path for data files using the --dbpath option to mongod.exe, for example: "C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe" --dbpath d:\test\mongodb\data If your path includes spaces, enclose the entire path in double quotes, for example: "C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe" --dbpath "d:\test\mongo db data" You may also specify the dbpath in a configuration file.

Step 2: Start MongoDB.

To start MongoDB, run mongod.exe. For example, from the Command Prompt: "C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe" This starts the main MongoDB database process. The waiting for connections message in the console output indicates that the mongod.exe process is running successfully. Depending on the security level of your system, Windows may pop up a Security Alert dialog box about blocking "some features" of C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe from communicating on networks. All users should select Private Networks, such as my home or work network and click Allow access. For additional information on security and MongoDB, please see the Security Documentation.

Step 3: Connect to MongoDB.

To connect to MongoDB through the mongo.exe shell, open another Command Prompt. "C:\Program Files\MongoDB\Server\3.6\bin\mongo.exe" If you want to develop applications using .NET, see the documentation of C# and MongoDB for more information.

Step 4: Begin using MongoDB.

To help you start using MongoDB, MongoDB provides Getting Started Guides in various driver editions. See Getting Started for the available editions. Before deploying MongoDB in a production environment, consider the Production Notes document. Later, to stop MongoDB, press Control+C in the terminal where the mongod instance is running.

Configure a Windows Service for MongoDB Community Edition

Step 1: Open an Administrator command prompt.

Press the Win key, type cmd.exe, and press Ctrl + Shift + Enter to run the Command Prompt as Administrator. Execute the remaining steps from the Administrator command prompt.

Step 2: Create directories.

Create directories for your database and log files: mkdir c:\data\db mkdir c:\data\log

Step 3: Create a configuration file.

Create a configuration file. The file must set systemLog.path. Include additional configuration options as appropriate. For example, create a file at C:\Program Files\MongoDB\Server\3.6\mongod.cfg that specifies both systemLog.path and storage.dbPath: systemLog: destination: file path: c:\data\log\mongod.log storage: dbPath: c:\data\db

Step 4: Install the MongoDB service.

Important: Run all of the following commands in Command Prompt with "Administrative Privileges". Install the MongoDB service by starting mongod.exe with the --install option and the -config option to specify the previously created configuration file. "C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --config "C:\Program Files\MongoDB\Server\3.4\mongod.cfg" --install To use an alternate dbpath, specify the path in the configuration file (e.g. C:\mongodb\mongod.cfg) or on the command line with the --dbpath option. If needed, you can install services for multiple instances of mongod.exe or mongos.exe. Install each service with a unique --serviceName and --serviceDisplayName. Use multiple instances only when sufficient system resources exist and your system design requires it.

Step 5: Start the MongoDB service.

net start MongoDB

Step 6: Stop or remove the MongoDB service as needed.

To stop the MongoDB service use the following command: net stop MongoDB To remove the MongoDB service use the following command: "C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --remove

Manually Create a Windows Service for MongoDB Community Edition

You can set up the MongoDB server as a Windows Service that starts automatically at boot time. The following procedure assumes you have installed MongoDB Community using the .msi installer with the path C:\Program Files\MongoDB\Server\3.4\. If you have installed in an alternative directory, you will need to adjust the paths as appropriate.

Step 1: Open an Administrator command prompt.

Press the Win key, type cmd.exe, and press Ctrl + Shift + Enter to run the Command Prompt as Administrator. Execute the remaining steps from the Administrator command prompt.

Step 2: Create directories.

Create directories for your database and log files: mkdir c:\data\db mkdir c:\data\log

Step 3: Create a configuration file.

Create a configuration file. The file must set systemLog.path. Include additional configuration options as appropriate. For example, create a file at C:\Program Files\MongoDB\Server\3.6\mongod.cfg that specifies both systemLog.path and storage.dbPath: systemLog: destination: file path: c:\data\log\mongod.log storage: dbPath: c:\data\db

Step 4: Create the MongoDB service.

Create the MongoDB service. sc.exe create MongoDB binPath= "\"C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe\" --service --config=\"C:\Program Files\MongoDB\Server\3.6\mongod.cfg\"" DisplayName= "MongoDB" start= "auto" sc.exe requires a space between "=" and the configuration values (eg "binPath= "), and a " to escape double quotes. If successfully created, the following log message will display: [SC] CreateService SUCCESS

Step 5: Start the MongoDB service.

net start MongoDB

Step 6: Stop or remove the MongoDB service as needed.

To stop the MongoDB service, use the following command: net stop MongoDB To remove the MongoDB service, first stop the service and then run the following command: sc.exe delete MongoDB

Connect to MongoDB via Mongo Shell

Introduction

The mongo shell is an interactive JavaScript interface to MongoDB. This tutorial demonstrates how to connect to MongoDB via the mongo shell. Once connected to MongoDB, you can use the mongo shell to query and update data as well as perform administrative operations.

Prerequisites

Local MongoDB Instance on Default Port

To connect to a MongoDB instance running on localhost with default port 27017:
  1. At a prompt in a terminal window (or a command prompt for Windows), go to your <mongodb installation dir>:
cd <mongodb installation dir>
  1. Type ./bin/mongo to start mongo:
./bin/mongo Alternatively, if you added the <mongodb installation dir>/bin to your PATH you can run mongo instead of ./bin/mongo: mongo

Local MongoDB Instance on a Non-default Port

Use the --port <port> command-line option to connect to a MongoDB instance running on localhost with a non-default port 28015: mongo --port 28015

MongoDB Instance on a Remote Host

Use the --host <host>:<port> command-line option to connect to a MongoDB instance running on a remote host machine: mongo --host mongodb0.tutorials.com:28015 Alternatively, pass the host and port parameters separately: mongo --host mongodb0.tutorials.com --port 28015

MongoDB Instance using Authentication

Use the --username <user> and --password <pass> command-line options to connect to a MongoDB instance that is using authentication: mongo --username alice --password abc123 --host mongodb0.tutorials.com --port 28015

Connect to MongoDB via the Python Driver

Introduction

PyMongo is a Python distribution containing tools for working with MongoDB. This tutorial demonstrates how to connect to MongoDB using the Pymongo driver.

Prerequisites

Local MongoDB Instance on Default Port

Pymongo uses the MongoClient for connecting to a MongoDB instance, replica set, or sharded cluster. If your MongoDB instance is running on the default host (localhost) and port (27017), you can instantiate a MongoClient without specifying any parameters: import pymongo from pymongo import MongoClient client = MongoClient() # Get the sampleDB database db = client.sampleDB

Connect Using Host and Port Parameters

The host and port can be specified explicitly by passing their respective values as parameters to the MongoClient. The following operation connects to a MongoDB instance running on a remote host using the host and port parameters: import pymongo from pymongo import MongoClient client = MongoClient('mongodb0.tutorials.com', 27017) # Get the sampleDB database db = client.sampleDB The default host and port can also be specified explicitly: import pymongo from pymongo import MongoClient client = MongoClient('localhost', 27017) # Get the sampleDB database db = client.sampleDB

Connect Using a URI

Pymongo also accepts a URI to connect to MongoDB: import pymongo from pymongo import MongoClient client = MongoClient('mongodb://localhost:27017') # Get the sampleDB database db = client.sampleDB

Connect with Authentication Credentials

To connect to a MongoDB instance with authentication enabled, specify a URI in the following format: mongodb://[username:password@]host1[:port1] The following operation connects the user alice with password abc123 to a MongoDB instance on the default host and port: import pymongo from pymongo import MongoClient client = MongoClient('mongodb://alice:abc123@localhost:27017') # Get the sampleDB database db = client.sampleDB

Notes

mongo pw: K..@M.. download:windows 64bit run the msi file select custom to select the installation path, setup a short name path and then all next after installation, create 2 folders in the mongodb folder to hold the log and database: data, log folders inside data folder create the db folder to store the database then open the cmd as administrator and goto the mongodb folder to run some commands cd d:\mongodb\bin run command to configure: mongod --directoryperdb --dbpath d:\mongodb\data\db --logpath d:\mongodb\log\mongo.log --logappend --rest --install or without rest mongod --directoryperdb --dbpath d:\mongodb\data\db --logpath d:\mongodb\log\mongo.log --logappend --install to start MongoDB services (note this starts the server): net start MongoDB or mongod --dbpath d:\mongodb\data\db or mongod to enter the mongo shell: mongo and then clear the screen: cls to show the dbs: show dbs to create new database: use customerdatabase creating the database will enter the database automatically to show the present database: db to create user for the database: db.createUser({ user: "brad", pwd: "1234", roles: ["readWrite", "dbAdmin"] }); to add data: db.createCollection("customers"); to show data in database: show collections to insert document: db.customers.insert({first_name:"john", last_name:"wo"}); to view the document: db.customers.find(); to insert multiple document (note the square bracket added and added field): db.customers.insert([{first_name:"lisa", last_name:"lo"}, {first_name:"bill", last_name:"bo", gender:"male"}]); to view the document formatted nice and neat: db.customers.find().pretty(); to upadte a document: db.customers.update({first_name:"john"}, {first_name:"john", last_name:"wo", gender:"male"}); to update set of documents, use set operator: db.customers.update({first_name:"john"}, {$set: {gender:"male"}}); to update set of documents with age: db.customers.update({first_name:"john"}, {$set: {age:45}}); to increment the age: db.customers.update({first_name:"john"}, {$ind: {age:5}}); to remove a field: db.customers.update({first_name:"john"}, {$unset: {age: 1}}); mongod is the primary daemon process for the MongoDB system. It handles data requests, manages data access, and performs background management operations. --directoryperdb Uses a separate directory to store data for each database. The directories are under the --dbpath directory, and each subdirectory name corresponds to the database name. --dbpath contains data files Default: /data/db on Linux and macOS, \data\db on Windows The directory where the mongod instance stores its data. --logpath Sends all diagnostic logging information to a log file instead of to standard output or to the host’s syslog system. MongoDB creates the log file at the path you specify. By default, MongoDB will move any existing log file rather than overwrite it. To instead append to the log file, set the --logappend option. --rest option Default: false Set to true to enable a simple REST interface. The mongod process includes a simple REST interface, generally used for monitoring/alerting scripts or administrative tasks. db.createUser(user, writeConcern) Creates a new user for the database on which the method is run. db.collection.insert() Inserts a document or documents into a collection.

Compass provides two methods to connect to your deployment

Using the connection string or Filling out deployment information in individual fields Using the connection string: Paste this string in the connection string field and hit CONNECT: mongodb+srv://m001-student:m001-mongodb-basics@cluster0-jxeqq.mongodb.net/test Filling out deployment information in individual fields If the connection string did not work for you, then you can manually fill in the individual fields and try to connect that way instead. Click on Fill in connection fields individually: https://university-courses.s3.amazonaws.com/M001/Compass_fill_in_fields.png Connecting to the class atlas cluster from the mongo shell Please use the following command to connect to the class Atlas cluster. Please note that the connection string shown below is different from what we have used in video. This does not affect the highly available nature of the cluster. For additional reading please refer the Optional Reading section below. mongo "mongodb+srv://cluster0-jxeqq.mongodb.net/test" --username m001-student -password m001-mongodb-basics If in case you are unable to connect using the srv connection string then please use the standard connection string as not all DNS providers or routing systems support the SRV protocol. mongo "mongodb://cluster0-shard-00-00-jxeqq.mongodb.net:27017,cluster0-shard-00-01-jxeqq.mongodb.net:27017,cluster0-shard-00-02-jxeqq.mongodb.net:27017/test?replicaSet=Cluster0-shard-0" --authenticationDatabase admin --ssl --username m001-student --password m001-mongodb-basics You should issue this command in the cmd shell, the OSX Terminal application, or another command-line interface of your choice. Windows users are recommended to use the PowerShell. Starting in MongoDB version 4.2, the ssl option has been deprecated and the new corresponding tls option has been added. The use of +srv connection string modifier in DNS Seedlist connection format automatically sets the tls option to true for the connection. The Atlas clusters we've looked at are replica sets. Replica sets are designed so that if the primary node goes down, one of the other nodes will step up to take its place so that clients can continue reading and writing data as if nothing had happened. The mongo shell is one such client.